<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>移动端输入法自带 emoji</title>
    <style>
        body {
            text-align: center;
        }
        input {
            height: 40px;
            width: 80%;
            margin-bottom: 10px;
            text-indent: 10px;
        }
    </style>
</head>

<body>
    <p>请输入手机输入法自带 emoji 表情，如：&#128525;</p>
    <input class="content" type="text">
    <input class="submit" type="submit" value="确定">
    <div class="content-emoji"></div>
    <div class="content-code"></div>

    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(".submit").on('click', function () {
            var val = $('.content').val()
            var v1 = utf16toEntities(val);
            var v2 = entitiestoUtf16(v1);
            $('.content-emoji').html('<p>您输入的表情：' + v2 + '</p>');
            $('.content-code').text('对应的实体字符：' + v1);
        })

        function utf16toEntities(str) {
            var patt = /[\ud800-\udbff][\udc00-\udfff]/g;
            // 检测utf16字符正则
            str = str.replace(patt, function (char) {
                var H, L, code;
                if (char.length === 2) {
                    H = char.charCodeAt(0);
                    // 取出高位
                    L = char.charCodeAt(1);
                    // 取出低位
                    code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00;
                    // 转换算法
                    return "&#" + code + ";";
                } else {
                    return char;
                }
            });
            return str;
        }
        function entitiestoUtf16(str) {
            // 检测出形如&#12345;形式的字符串
            var strObj = utf16toEntities(str);
            var patt = /&#\d+;/g;
            var H, L, code;
            var arr = strObj.match(patt) || [];
            for (var i = 0; i < arr.length; i++) {
                code = arr[i];
                code = code.replace('&#', '').replace(';', '');
                // 高位
                H = Math.floor((code - 0x10000) / 0x400) + 0xD800;
                // 低位
                L = (code - 0x10000) % 0x400 + 0xDC00;
                code = "&#" + code + ";";
                var s = String.fromCharCode(H, L);
                strObj.replace(code, s);
            }
            return strObj;
        } 
    </script>
</body>

</html>
